package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apkfuns.logutils.LogUtils;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.api.BusinessPayPassword;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.EducationVO;
import com.digitalchina.lxnsy.entity.ExpertTypeVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.entity.PersonalInfoVO;
import com.digitalchina.lxnsy.entity.SexVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.SharedPreferencesUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.ChannelXML;
import com.digitalchina.lxnsy.xml.ExpertInfoXML;
import com.digitalchina.lxnsy.xml.PersonalInfoXML;
import com.digitalchina.lxnsy.xml.RongCloudXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okhttputils.model.HttpParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.digitalchina.lxnsy.constant.MSG.MSG_FILE_UPLOAD_SUCCESS;
import static com.digitalchina.lxnsy.toolkit.DateUtil.DateToString;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/3/23 10:48
 * 修改备注：
 * ================================================
 */
public class AccountPersonManagementActivity extends BaseActivity {


    @Bind(R.id.iv_person_avatar)
    SimpleDraweeView ivPersonAvatar;
    @Bind(R.id.tv_person_username)
    TextView tvPersonUsername;
    @Bind(R.id.tv_person_nickname)
    TextView tvPersonNickname;
    @Bind(R.id.tv_person_sex)
    TextView tvPersonSex;
    @Bind(R.id.tv_person_birthday)
    TextView tvPersonBirthday;
    @Bind(R.id.tv_person_true_name)
    TextView tvPersonTrueName;
    @Bind(R.id.tv_person_id_number)
    TextView tvPersonIdNumber;
    @Bind(R.id.tv_person_education)
    TextView tvPersonEducation;
    @Bind(R.id.tv_person_email)
    TextView tvPersonEmail;
    @Bind(R.id.tv_person_address)
    TextView tvPersonAddress;
    @Bind(R.id.tv_person_industry)
    TextView tvPersonIndustry;
    @Bind(R.id.tv_person_scale)
    TextView tvPersonScale;
    @Bind(R.id.tv_person_hobby)
    TextView tvPersonHobby;
    @Bind(R.id.tv_person_mobile_phone)
    TextView tvPersonMobilePhone;

    // 图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    @Bind(R.id.progress_bar_percent)
    ProgressBar progressBarPercent;
    @Bind(R.id.tv_percent)
    TextView tvPercent;

    private ArrayList<ImageItem> selectedImageList = new ArrayList<>(); //当前选择的所有图片
    private String filePath = ""; // 图片地址

    // ===============================
    public static final int REQUEST_CODE_EDIT = 99;
    private int msgWhat;
    private String mKey, mValue;
    private String fileName = "";

    // 时间选择器
    private TimePickerView pvTime;
    // 性别选择器 , 产业选择器
    private OptionsPickerView pvSex, pvOptions;
    private List<SexVO> sexVOList = new ArrayList<>();
    // 学历选择器
    private OptionsPickerView pvEducation;
    private List<EducationVO> educationVOList = new ArrayList<>();

    private List<ExpertTypeVO> expertTypeVOList = new ArrayList<>(); // 一级菜单
    private List<List<ExpertTypeVO.ChildTypesBean>> listList = new ArrayList<>(); // 二级菜单

    // 区域code
    private String provinceCode = "";
    private String cityCode = "";
    private String countyCode = "";

    // 产业信息
    private String mFirstIndustryCode = "";
    private String mFirstIndustryName = "";
    private String mIndustryCode = "";
    private String mIndustryName = "";

    // 兴趣爱好
    private String mHobbiesName = "";
    private String mHobbiesCode = "";

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_account_person_management);
        setTitle("账户管理");
    }

    @Override
    public void initMember() {

        tvPersonUsername.setText(UserXML.getUseraccName(AccountPersonManagementActivity.this));

        // 优先加载本地数据
        setTextViewForXML();


//        // 获取个人信息
//        BusinessAccount.getPersonalInfoById(AccountPersonManagementActivity.this, mHandler);

        //最好等数据加载完毕再初始化并显示，以免数据量大的时候，还未加载完毕就显示，造成APP崩溃
        initTimePicker();
        initSexData();
        initEducationData();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 手机号码取userXML
//        String pStrMobile = UserXML.getMobilePhone(AccountPersonManagementActivity.this);
//        tvPersonMobilePhone.setText(pStrMobile.replaceAll("(?<=[\\d]{3})\\d(?=[\\d]{4})", "*"));
    }

    /**
     * 设置XML
     */
    private void setTextViewForXML() {
        FrescoUtil.showImageSmall(PersonalInfoXML.getHeadportrait(AccountPersonManagementActivity.this), ivPersonAvatar);
        tvPersonNickname.setText(PersonalInfoXML.getNiceName(AccountPersonManagementActivity.this));
        if (PersonalInfoXML.getUserSex(AccountPersonManagementActivity.this).equals("1"))
            tvPersonSex.setText("男");
        else if (PersonalInfoXML.getUserSex(AccountPersonManagementActivity.this).equals("0"))
            tvPersonSex.setText("女");
        else
            tvPersonSex.setText("");
        tvPersonBirthday.setText(DateUtil.getDate(PersonalInfoXML.getUserBirthday(AccountPersonManagementActivity.this), DateStyle.YYYY_MM_DD));
        tvPersonTrueName.setText(PersonalInfoXML.getTrueName(AccountPersonManagementActivity.this));
        tvPersonIdNumber.setText(PersonalInfoXML.getIdCardNO(AccountPersonManagementActivity.this));
        switch (PersonalInfoXML.getEducationCode(AccountPersonManagementActivity.this)) {
            case "1401":
                tvPersonEducation.setText("小学");
                break;
            case "1402":
                tvPersonEducation.setText("初中");
                break;
            case "1403":
                tvPersonEducation.setText("高中");
                break;
            case "1404":
                tvPersonEducation.setText("大学及以上");
                break;
        }
        tvPersonEmail.setText(PersonalInfoXML.getUserEmail(AccountPersonManagementActivity.this));
        tvPersonAddress.setText(PersonalInfoXML.getAddress(AccountPersonManagementActivity.this));
        tvPersonIndustry.setText(PersonalInfoXML.getFirstIndustryName(AccountPersonManagementActivity.this) + " " + PersonalInfoXML.getIndustryName(AccountPersonManagementActivity.this));
        tvPersonScale.setText(PersonalInfoXML.getDimensions(AccountPersonManagementActivity.this));
        tvPersonHobby.setText(PersonalInfoXML.getHobbiesName(AccountPersonManagementActivity.this).replace(";", " "));


        setProgressBarPercent();

    }

    /**
     * 设置进度条数据
     */
    private void setProgressBarPercent() {
        List<TextView> textViewList = new ArrayList<>(); // 填写字段的textView
        int sum = 13; // 需要维护字段的总数
        int writeNum = 0; // 当前已经维护的字段
        if (!StringUtil.isStrEmpty(PersonalInfoXML.getHeadportrait(AccountPersonManagementActivity.this)))
            writeNum++;

        textViewList.add(tvPersonUsername); // 用户名 必填
        textViewList.add(tvPersonNickname);
        textViewList.add(tvPersonSex);
        textViewList.add(tvPersonBirthday);
        textViewList.add(tvPersonTrueName);
        textViewList.add(tvPersonIdNumber);
        textViewList.add(tvPersonEducation);
        textViewList.add(tvPersonEmail);
        textViewList.add(tvPersonAddress);
        textViewList.add(tvPersonIndustry);
        textViewList.add(tvPersonScale);
        textViewList.add(tvPersonHobby);

        for (int i = 0; i < textViewList.size(); i++) {
            if (!StringUtil.isTextEmpty(textViewList.get(i)))
                writeNum++;
        }

        double percent = (double) writeNum / sum * 100;
        progressBarPercent.setProgress((int) percent);
        tvPercent.setText((int) percent + "%");

    }


    /**
     * 学历选择器
     */
    private void initEducationData() {

        educationVOList.add(new EducationVO("小学", "1401"));
        educationVOList.add(new EducationVO("初中", "1402"));
        educationVOList.add(new EducationVO("高中", "1403"));
        educationVOList.add(new EducationVO("本科及以上", "1404"));

        pvEducation = new OptionsPickerView.Builder(AccountPersonManagementActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("educationCode", educationVOList.get(options1).getCode()), mHandler);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvEducation.setPicker(educationVOList);
    }


    /**
     * 性别选择器
     */
    private void initSexData() {

        sexVOList.add(new SexVO("男", "1"));
        sexVOList.add(new SexVO("女", "0"));

        pvSex = new OptionsPickerView.Builder(AccountPersonManagementActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

//                String tx = sexVOList.get(options1).getPickerViewText();
                BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("userSex", sexVOList.get(options1).getCode()), mHandler);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvSex.setPicker(sexVOList);
    }


    /**
     * 时间选择器
     */
    private void initTimePicker() {

        int start = 1900;
        int endDate = Calendar.getInstance().get(Calendar.YEAR);

        //控制时间范围,setRange方法 要在setDate 之前才有效果(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        /*Calendar calendar = Calendar.getInstance();*/

        //时间选择器
        pvTime = new TimePickerView.Builder(AccountPersonManagementActivity.this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (DateUtil.isRightDate(DateToString(date, DateStyle.YYYY_MM_DD), "yyyy-MM-dd"))
                    BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("userBirthday", DateToString(date, DateStyle.YYYY_MM_DD)), mHandler);
                else
                    showToast("所选日期不能是未来的日期");
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//default is all
                .setLabel("年", "月", "日", "", "", "") //设置空字符串以隐藏单位提示   hide label
                .setRange(start, endDate)
                .build();
    }

    /**
     * 产业选择器
     */
    private void initOptionPicker(String json) {//条件选择器初始化

        expertTypeVOList = FastJsonUtil.getListBean(json, "body", "tradeTypes", ExpertTypeVO.class);

        if (expertTypeVOList == null || expertTypeVOList.size() == 0)
            return;

        for (int i = 0; i < expertTypeVOList.size(); i++) {
            if (expertTypeVOList.get(i).getChildTypes() == null || expertTypeVOList.get(i).getChildTypes().size() == 0) {
                expertTypeVOList.remove(i);
                i--;
            } else
                listList.add(expertTypeVOList.get(i).getChildTypes());
        }

        pvOptions = new OptionsPickerView.Builder(AccountPersonManagementActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                ExpertTypeVO typeVO = expertTypeVOList.get(options1);
                ExpertTypeVO.ChildTypesBean listBean = listList.get(options1).get(option2);

                mFirstIndustryCode = typeVO.getCode();
                mFirstIndustryName = typeVO.getName();
                mIndustryCode = listBean.getCode();
                mIndustryName = listBean.getName();
                BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("typeCode", listBean.getCode()), mHandler);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0, 0)  //设置默认选中项
//                .isDialog(true)//设置为对话框模式
                .build();

        pvOptions.setPicker(expertTypeVOList, listList);

        pvOptions.show();
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (AccountPersonManagementActivity.this == null)
                    return;

                msgWhat = msg.what;
                switch (msgWhat) {
                    case MSG_FILE_UPLOAD_SUCCESS:  // 上传图片
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_GET_PERSONAL_INFO_BY_ID_SUCCESS: // 获取个人信息
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_PERSONAL_INFO_BY_ID_FIELD:
                        LogUtils.e(msg.obj);
                        break;
                    case MSG.MSG_EDIT_PERSONAL_INFO_BY_ID_SUCCESS: // 修改个人信息
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_EDIT_PERSONAL_INFO_BY_ID_FIELD:
                        dismissDialog();
                        break;
                    case MSG.MSG_GET_TRADE_TYPE_SUCCESS: // 产业分类
                        callBack(msg.obj.toString());
                        break;
                    case MSG.MSG_GET_TRADE_TYPE_FIELD:
                        break;
                    case MSG.MSG_HAVE_PAY_PASSWORD_SUCCESS: // 查询用户是否设置支付密码
                        String havePayPassword = FastJsonUtil.getString(msg.obj.toString(), "havePayPassword");
                        if ("0".equals(havePayPassword)) {
                            new MaterialDialog.Builder(AccountPersonManagementActivity.this)
                                    .title("提示")
                                    .content("您还没有设置过提现密码，是否现在设置？")
                                    .positiveText("去设置")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            GotoUtil.gotoActivity(AccountPersonManagementActivity.this, SetPayPasswordOneActivity.class,"type",0);
                                        }
                                    })
                                    .show();
                        } else
                            GotoUtil.gotoActivity(AccountPersonManagementActivity.this, AmendPayPasswordActivity.class);
                        break;
                    case MSG.MSG_HAVE_PAY_PASSWORD_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        switch (msgWhat) {
            case MSG_FILE_UPLOAD_SUCCESS:  // 上传图片成功后 返回FileName
                FileVO fileVO = FastJsonUtil.getBean(object.toString(), "body", "fileStorage", FileVO.class);
                if (fileVO == null)
                    return;
                // 这里还需要修改个人信息接口对应的头像FileName
                fileName = fileVO.getName();
                BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("headPortrait", fileName), mHandler);
                break;
            case MSG.MSG_GET_PERSONAL_INFO_BY_ID_SUCCESS: // 获取个人信息
                try {
                    // 储存兴趣爱好ALL JSON 到XML
                    String body = new JSONObject(object.toString()).getString("body");
                    String hobby = new JSONObject(body).getString("allHobby");
                    PersonalInfoXML.setAllHobbiesJson(AccountPersonManagementActivity.this, hobby);
                    // 储存个人信息
                    savePersonalInfo(object.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case MSG.MSG_EDIT_PERSONAL_INFO_BY_ID_SUCCESS:
                dismissDialog();
                saveToXML();
                break;
            case MSG.MSG_GET_TRADE_TYPE_SUCCESS: // 产业分类
                initOptionPicker(object.toString());
                break;

        }
    }

    /**
     * 上传信息后保存到XML
     */
    private void saveToXML() {
        switch (mKey) {
            case "headPortrait":
                PersonalInfoXML.setHeadportrait(AccountPersonManagementActivity.this, mValue);
                break;
            case "niceName":
                PersonalInfoXML.setNiceName(AccountPersonManagementActivity.this, mValue);
                break;
            case "userEmail":
                PersonalInfoXML.setUserEmail(AccountPersonManagementActivity.this, mValue);
                break;
            case "address":
                PersonalInfoXML.setAddress(AccountPersonManagementActivity.this, mValue);
                PersonalInfoXML.setProvinceCode(AccountPersonManagementActivity.this, provinceCode);
                PersonalInfoXML.setCityCode(AccountPersonManagementActivity.this, cityCode);
                PersonalInfoXML.setCountyCodeCode(AccountPersonManagementActivity.this, countyCode);
                break;
            case "dimensions":
                PersonalInfoXML.setDimensions(AccountPersonManagementActivity.this, mValue);
                break;
            case "userSex":
                PersonalInfoXML.setUserSex(AccountPersonManagementActivity.this, mValue);
                break;
            case "userBirthday":
                PersonalInfoXML.setUserBirthday(AccountPersonManagementActivity.this, mValue);
                break;
            case "trueName":
                PersonalInfoXML.setTrueName(AccountPersonManagementActivity.this, mValue);
                break;
            case "idCardNo":
                PersonalInfoXML.setIdCardNO(AccountPersonManagementActivity.this, mValue);
                break;
            case "educationCode":
                PersonalInfoXML.setEducationCode(AccountPersonManagementActivity.this, mValue);
                break;
            case "typeCode":
                PersonalInfoXML.setIndustry(AccountPersonManagementActivity.this, mValue); // 展示1-2级name
                PersonalInfoXML.setFirstIndustryCode(AccountPersonManagementActivity.this, mFirstIndustryCode);
                PersonalInfoXML.setFirstIndustryName(AccountPersonManagementActivity.this, mFirstIndustryName);
                PersonalInfoXML.setIndustryCode(AccountPersonManagementActivity.this, mIndustryCode);
                PersonalInfoXML.setIndustryName(AccountPersonManagementActivity.this, mIndustryName);
                break;
            case "hobbies":
                PersonalInfoXML.setHobbiesCode(AccountPersonManagementActivity.this, mHobbiesCode);
                PersonalInfoXML.setHobbiesName(AccountPersonManagementActivity.this, mHobbiesName);
                break;
        }

        setTextViewForXML();


    }



    /**
     * 编辑除了地址个人信息
     *
     * @param key
     * @param value
     * @return
     */
    private HttpParams editPersonal(String key, String value) {

        showDialog("请稍候...");

        mKey = key;
        mValue = value;
        HttpParams params = new HttpParams();
        /**
         headPortrait    头像
         niceName        昵称
         trueName        真实姓名
         userSex         性别
         userBirthday    生日
         educationCode   学历
         idCardNo        身份证号
         userEmail       电子邮箱
         hobbies         兴趣爱好  以；分割的字符串
         typeCode        产业编号 二级编码
         dimensions      产业规模
         provinceCode   省编码
         cityCode       城市编码
         countyCode     地区编码
         */
        params.put("userAccId", UserXML.getUserId(AccountPersonManagementActivity.this));
        params.put("headPortrait", key.equals("headPortrait") ? value : PersonalInfoXML.getHeadportrait(AccountPersonManagementActivity.this));
        params.put("niceName", key.equals("niceName") ? value : PersonalInfoXML.getNiceName(AccountPersonManagementActivity.this));
        params.put("trueName", key.equals("trueName") ? value : PersonalInfoXML.getTrueName(AccountPersonManagementActivity.this));
        params.put("userSex", key.equals("userSex") ? value : PersonalInfoXML.getUserSex(AccountPersonManagementActivity.this));
        params.put("userBirthday", key.equals("userBirthday") ? value : PersonalInfoXML.getUserBirthday(AccountPersonManagementActivity.this));
        params.put("idCardNo", key.equals("idCardNo") ? value : PersonalInfoXML.getIdCardNO(AccountPersonManagementActivity.this));
        params.put("educationCode", key.equals("educationCode") ? value : PersonalInfoXML.getEducationCode(AccountPersonManagementActivity.this));
        params.put("userEmail", key.equals("userEmail") ? value : PersonalInfoXML.getUserEmail(AccountPersonManagementActivity.this));
        params.put("hobbies", key.equals("hobbies") ? value : PersonalInfoXML.getHobbiesCode(AccountPersonManagementActivity.this));
        params.put("typeCode", key.equals("typeCode") ? value : PersonalInfoXML.getIndustryCode(AccountPersonManagementActivity.this));
        params.put("dimensions", key.equals("dimensions") ? value : PersonalInfoXML.getDimensions(AccountPersonManagementActivity.this));

        params.put("provinceCode", PersonalInfoXML.getProvinceCode(AccountPersonManagementActivity.this));
        params.put("cityCode", PersonalInfoXML.getCityCode(AccountPersonManagementActivity.this));
        params.put("countyCode", PersonalInfoXML.getCountyCodeCode(AccountPersonManagementActivity.this));

        return params;
    }

    /**
     * 修改地址name和code
     *
     * @param key   address
     * @param value
     * @return
     */
    private HttpParams editAddress(String key, String value, String code[]) {

        showDialog("请稍候...");

        mKey = key;
        mValue = value;
        HttpParams params = new HttpParams();
        /**
         provinceCode   省编码
         cityCode       城市编码
         countyCode     地区编码
         */
        params.put("userAccId", UserXML.getUserId(AccountPersonManagementActivity.this));
        params.put("headPortrait", PersonalInfoXML.getHeadportrait(AccountPersonManagementActivity.this));
        params.put("niceName", PersonalInfoXML.getNiceName(AccountPersonManagementActivity.this));
        params.put("trueName", PersonalInfoXML.getTrueName(AccountPersonManagementActivity.this));
        params.put("userSex", PersonalInfoXML.getUserSex(AccountPersonManagementActivity.this));
        params.put("userBirthday", PersonalInfoXML.getUserBirthday(AccountPersonManagementActivity.this));
        params.put("educationCode", PersonalInfoXML.getEducationCode(AccountPersonManagementActivity.this));
        params.put("idCardNo", PersonalInfoXML.getIdCardNO(AccountPersonManagementActivity.this));
        params.put("userEmail", PersonalInfoXML.getUserEmail(AccountPersonManagementActivity.this));
        params.put("hobbies", PersonalInfoXML.getHobbiesCode(AccountPersonManagementActivity.this));
        params.put("typeCode", PersonalInfoXML.getIndustryCode(AccountPersonManagementActivity.this));
        params.put("dimensions", PersonalInfoXML.getDimensions(AccountPersonManagementActivity.this));

        params.put("provinceCode", code[0]);
        params.put("cityCode", code[1]);
        params.put("countyCode", code[2]);

        return params;
    }

    /**
     * 储存个人信息到xml
     *
     * @param json
     */
    private void savePersonalInfo(String json) {

        // 个人信息
        final PersonalInfoVO personalInfoVO = FastJsonUtil.getBean(json, "body", "personalInfo", PersonalInfoVO.class);
        if (personalInfoVO != null) {
            PersonalInfoXML.setPersonalInfoVO(AccountPersonManagementActivity.this, personalInfoVO);
            setTextViewForXML();
        }
    }

    /**
     * 获取兴趣爱好List 返回字符串集合
     *
     * @param hobbiesBeen
     * @return
     */
    private String getHobbies(List<PersonalInfoVO.HobbiesBean> hobbiesBeen) {
        String hobbies = "";
        if (hobbiesBeen != null && hobbiesBeen.size() > 0)
            for (int i = 0; i < hobbiesBeen.size(); i++)
                hobbies += hobbiesBeen.get(i).getHobbyName() + " ";

        return hobbies;
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    /**
     * onclick监听
     *
     * @param view
     */
    @OnClick({R.id.rl_personal_avatar, R.id.rl_personal_nickname, R.id.rl_personal_sex, R.id.rl_personal_birthday, R.id.rl_personal_true_name, R.id.rl_personal_id_number,
            R.id.rl_personal_education, R.id.rl_personal_email, R.id.rl_personal_industry, R.id.rl_personal_scale, R.id.rl_personal_address, R.id.rl_personal_hobby,
            R.id.rl_personal_mobile_phone, R.id.rl_personal_update_pwd, R.id.btn_person_exit, R.id.rl_pay_pwd,R.id.rl_auth_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_personal_avatar: // 头像
                selectImage();
                break;
            case R.id.rl_personal_nickname: // 昵称
                gotoEditActivity("niceName");
                break;
            case R.id.rl_personal_sex: // 性别
                pvSex.show();
                break;
            case R.id.rl_personal_birthday: // 生日
                pvTime.show(); //弹出时间选择器
                break;
            case R.id.rl_personal_true_name: // 真实姓名
                gotoEditActivity("trueName");
                break;
            case R.id.rl_personal_id_number: // 身份证号
                gotoEditActivity("idCardNo");
                break;
            case R.id.rl_personal_education: // 学历
                pvEducation.show(); //弹出学历选择
                break;
            case R.id.rl_personal_email: // 邮箱
                gotoEditActivity("userEmail");
                break;
            case R.id.rl_personal_industry: // 产业
                if (expertTypeVOList != null && expertTypeVOList.size() > 0)
                    pvOptions.show();
                else
                    // 获取所有类型
                    BusinessAccount.getTradeTypeList(AccountPersonManagementActivity.this, mHandler);
                break;
            case R.id.rl_personal_scale: // 规模
                gotoEditActivity("dimensions");
                break;
            case R.id.rl_personal_address: // 所在区域
                showAddressPicker();
                break;
            case R.id.rl_personal_hobby: // 兴趣爱好
                Intent intent = new Intent(AccountPersonManagementActivity.this, HobbyActivity.class);
                intent.putExtra("type", "hobbies");
                startActivityForResult(intent, REQUEST_CODE_EDIT);
                break;
            case R.id.rl_personal_mobile_phone: // 修改手机
                GotoUtil.gotoActivity(AccountPersonManagementActivity.this, MobilePhoneIdentificationStepOneActivity.class);
                break;
            case R.id.rl_personal_update_pwd: // 修改密码
                GotoUtil.gotoActivity(AccountPersonManagementActivity.this, UpdatePasswordActivity.class);
                break;
            case R.id.rl_pay_pwd: // 设置支付密码
                BusinessPayPassword.havePayPassword(this, mHandler);
                break;
            case R.id.rl_auth_login: // 第三方授权登陆
                GotoUtil.gotoActivity(AccountPersonManagementActivity.this, AuthLoginListActivity.class);
                break;
            case R.id.btn_person_exit: // 退出帐号
                new MaterialDialog.Builder(AccountPersonManagementActivity.this)
                        .title("提示")
                        .content("您确定要退出登录吗？")
                        .positiveText("确定")
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                SharedPreferencesUtil.cleanXml(AccountPersonManagementActivity.this, UserXML.XML_NAME_USER);
                                SharedPreferencesUtil.cleanXml(AccountPersonManagementActivity.this, PersonalInfoXML.XML_NAME_PERSONAL_INFO);
                                SharedPreferencesUtil.cleanXml(AccountPersonManagementActivity.this, RongCloudXML.XML_NAME_RONG);
                                SharedPreferencesUtil.cleanXml(AccountPersonManagementActivity.this, ExpertInfoXML.XML_NAME_EXPERT_INFO);
                                SharedPreferencesUtil.cleanXml(AccountPersonManagementActivity.this, ChannelXML.XML_NAME_CHANNEL);
                                clearJPushAlias();
//                                finish();
                                ActivityTaskManager.getInstance().closeAllActivity();
                                GotoUtil.gotoActivity(AccountPersonManagementActivity.this, LoginActivity.class, "logout", "");
                            }
                        })
                        .show();
                break;
        }
    }

    /**
     * 取消极光别名设置
     */
    private void clearJPushAlias() {
        JPushInterface.setAlias(this, "", new TagAliasCallback() {
            @Override
            public void gotResult(int code, String s, Set<String> set) {
                if (code == 0) { // 成功
                    LogUtils.e("JPush alias cancel success");
                } else if (code == 6002) { // 超时
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            JPushInterface.setAlias(AccountPersonManagementActivity.this, "", null);
                        }
                    }, 1000 * 60);
                } else { // 失败
                    LogUtils.e("Failed with errorCode = " + code);
                }
            }
        });
    }

    /**
     * 所在区域选择
     */
    private void showAddressPicker() {
        final BottomDialog bottomDialog = new BottomDialog(AccountPersonManagementActivity.this);
        bottomDialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                provinceCode = province.province_code;
                cityCode = city != null ? city.city_code : "";
                countyCode = county != null ? county.county_code : "";
                String code[] = new String[3];
                code[0] = provinceCode;
                code[1] = cityCode;
                code[2] = countyCode;
                BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editAddress("address", String.format("%s %s %s", province.province_name,
                        city != null ? city.city_name : "", county != null ? county.county_name : ""), code), mHandler);
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }

    /**
     * 跳转到编辑页面
     *
     * @param type 标记修改的类型
     */
    private void gotoEditActivity(String type) {
        Intent intent = new Intent(AccountPersonManagementActivity.this, EditPersonalInfoActivity.class);
        intent.putExtra("type", type);
        startActivityForResult(intent, REQUEST_CODE_EDIT);
    }

    /**
     * 修改头像跳转至自定义相册
     */
    private void selectImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(380);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(380);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(400);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(400);//保存文件的高度。单位像素
        Intent intent = new Intent(AccountPersonManagementActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SELECT);
    }

    /**
     * 跳转回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_EDIT) {

            switch (data.getStringExtra("type")) {
                case "niceName": // 昵称
                    BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("niceName", data.getStringExtra("edit")), mHandler);
                    break;
                case "trueName": // 真实姓名
                    BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("trueName", data.getStringExtra("edit")), mHandler);
                    break;
                case "idCardNo": // 身份证号
                    BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("idCardNo", data.getStringExtra("edit")), mHandler);
                    break;
                case "userEmail": // 邮箱
                    BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("userEmail", data.getStringExtra("edit")), mHandler);
                    break;
                case "dimensions": // 规模
                    BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("dimensions", data.getStringExtra("edit")), mHandler);
                    break;
                case "hobbies": // 兴趣爱好
                    mHobbiesCode = data.getStringExtra("hobbiesCode");
                    mHobbiesName = data.getStringExtra("hobbiesName");
                    BusinessAccount.editPersonalBaseInfo(AccountPersonManagementActivity.this, editPersonal("hobbies", mHobbiesCode), mHandler);
                    break;
            }

        } else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                showDialog("上传中,请稍候!");
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                filePath = images.get(0).path;
                selectedImageList.addAll(images);
                BusinessFile.imageCompressAndUpload(AccountPersonManagementActivity.this, filePath, mHandler);
            }
        }
    }
}
